//
//  OAuthViewController.swift
//  mySina
//
//  Created by mac on 15/12/17.
//  Copyright © 2015年 tz. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    let webview = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
        loadOAthPage()
    }
    //MARK: 设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "defaultAccount")
    }
    //导航条按钮的跳转
    @objc private func close() {
        dismissViewControllerAnimated(false, completion: nil)
    }
    @objc private func defaultAccount() {
        let jsString = "document.getElementById('userId').value = 'tianzhong588@163.com' ,document.getElementById('passwd').value = 'tian1992' "
        webview.stringByEvaluatingJavaScriptFromString(jsString)
    }
    override func loadView() {
        view = webview
        //设置代理
        webview.delegate = self
    }
    //MARK: 加载授权页面
    private func loadOAthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        webview.loadRequest(NSURLRequest(URL: url!))
    }
}
//MARK: extension可以使相关的代码更加模块化，易于管理和维护
extension OAuthViewController:UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //跳转页面的时候就会调用此方法
    //shouldStartLoadWithRequest 外部参数  navigationType 内部参数
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //需要根据请求的Url，去屏蔽不需要加载的数据
        //absoluteString 将URL转化成字符串
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        //希望加载的页面
        if urlString.hasPrefix("https://api.weibo.com/") {
            return true
        }
        //一定不是请求成功的回调，也一定不会是我们希望加载的页面
        if !urlString.hasPrefix("http://www.baidu.com") {
            return false
        }
        //程序运行到此处，一定是运行成功的回调
//        print(urlString)
        //解析字符串，获取code码
        let query = request.URL?.query
//        print(query)
        if let q = query {
            //字符串截取操作
            let codeStr = "code="
            //获取请求Token所需所需的code码
            let code = q.substringFromIndex(codeStr.endIndex)
//            print(code)
            loadAccessToken(code)
        }
        return true
    }
    //加载用户请求的token
    private func loadAccessToken(code:String) {
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                print("登陆成功")
//                //动画结束的时候，发出界面切换的通知
//                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: nil)
//                self.close()
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //等待 被modal出来的页面 彻底被回收是 再发出页面切换的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                })
            } else {
                print("登陆失败")
            }
        }
    }
}